package com.unknow.first.dapp.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lianziyou.chain.common.api.CommonResult;
import com.unknow.first.dapp.admin.mapper.TAddressInfo;
import com.unknow.first.dapp.admin.service.TAddressInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.cloud.annotation.SystemResource;
import org.cloud.constant.CoreConstant;
import org.cloud.constant.CoreConstant.AuthMethod;
import org.cloud.context.RequestContextManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/addressInfo")
@Slf4j
@SystemResource(path = "/addressInfo")
@Api(value = "地址信息相关API", tags = "地址信息相关API")
public class AddressInfoController {

    @Autowired
    private TAddressInfoService addressInfoService;

    @SystemResource(value = "/admin-getTeamTree", description = "管理员获取团队树状数据", authMethod = CoreConstant.AuthMethod.BYUSERPERMISSION)
    @RequestMapping(method = RequestMethod.GET, value = "/getTeamTree")
    @ApiOperation("管理员获取团队树状数据")
    public CommonResult<List<TAddressInfo>> getTeamTree(String parentAddress, String address) {
        return CommonResult.success(addressInfoService.getTeamTree(parentAddress, address));
    }

    @RequestMapping(method = RequestMethod.GET, value = "/isBind")
    @ApiOperation("判断地址是否绑定关系")
    public CommonResult<Boolean> isBind(@RequestParam(required = false,value = "address") String address) {

        if(!StringUtils.hasLength(address)){
            address = RequestContextManager.single().getRequestContext().getUser().getUsername();
        }
        LambdaQueryWrapper<TAddressInfo> queryWrapper = Wrappers.lambdaQuery(TAddressInfo.class).eq(TAddressInfo::getAddress, address).isNotNull(TAddressInfo::getParentAddress);
        TAddressInfo addressInfo = addressInfoService.getOne(queryWrapper, false);
        return CommonResult.success(addressInfo != null);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/bind")
    @SystemResource(value = "/user-bind-parent", description = "绑定上级地址", authMethod = AuthMethod.ALLSYSTEMUSER)
    @ApiOperation("绑定上级地址")
    public CommonResult<Boolean> bind(String parentAddress) throws Exception {
        return CommonResult.success(addressInfoService.bind(parentAddress, RequestContextManager.single().getRequestContext().getUser().getUsername()));
    }

}
